<template>
	<view class="Contain"> <!-- Contain Start -->
		<!-- <view style="width:120rpx; box-sizing:border-box; margin:10rpx;">
			<u-button type="primary" color="#ebecee" icon="arrow-left" text="返回" size="small" @click="back"></u-button>
		</view> -->
		<view class="orderInfo" v-if="ProductList.data[0] != undefined" >
					<view class="HomeAd" v-if="ProductList.data[0] != undefined">
						<u-row gutter="0">
							<u-col span="1" text-align="center">
								<view style="position:relative;left:-12px;">
								<u-checkbox :checked="allchecked" :disabled="false" shape="circle" size="20" @change="selectAll"></u-checkbox>
								</view>
							</u-col>
							<u-col span="2" text-align="center">
								<view style="position:relative;left:-7px;"><image :src="$globalConfig.shopLogo"></image></view>
							</u-col>
							<u-col span="6" text-align="left">
								<view>{{$globalConfig.shopName}}</view>
							</u-col>
							<u-col span="3" text-align="right">
								<!-- <view class="link">店铺首页</view> -->
							</u-col>
						</u-row>	
					</view> <!-- HomeAd End -->
					<view class="Photo">
						<view class="boxlist" v-for="(item,index) in ProductList.data" :key="index" style="margin-bottom:50rpx;">
								<u-row gutter="0">
									<u-col span="1" text-align="center">
									<u-checkbox v-if="item.isOver<1" :checked="item.checked" :disabled="false" shape="circle" size="20" @change="ChangeItem(index)"></u-checkbox>
									</u-col>
									<!-- /static/shop/sh1.png -->
									<u-col span="3" text-align="center"> 
										<view class="pimg">
											<view><image class="itemImage" :src="item.picUrl" :class="item.isOver===1?'imgGray':''" mode="aspectFill"></image></view>
											<view class="needDoctor" v-if="item.needDoctor>0">授</view>
										</view>
									</u-col>
									<u-col span="8" text-align="left">
										<view style="position:relative; top:20rpx;">
											<view class="black mid ptit" :class="item.isOver===1?'GrayThrough':''">{{item.goodsName}}</view>
											<!-- <view class="black mid ptit">{{item.id}}</view> -->
											<view class="kucun gray small" style="margin:10rpx 0;">{{item.classifyName}}</view>
											<view class="price mr-5">
												<view class="pa" :class="item.isOver===1?'GrayThrough':''"><text :class="item.isOver===1?'GrayText':''">￥</text>{{item.discountPrice}}</view>
												<view class="pb"><u-number-box :disabledInput="true" v-if="item.isOver<1" :min="1" v-model="item.num" @change="boxvalChange(index)"></u-number-box></view>
											</view>
											<view class="del">
												<view class="tip"><text v-if="item.isOver===1">商品库存不足或已下架</text></view>
												<view @click="del(index,item.id,item.goodsName)">移除</view>
											</view>
										</view>
									</u-col> 
								</u-row>
						</view> <!-- boxlist End -->
					</view> <!-- Photo End -->
		</view> <!-- orderInfo End -->
		<view v-else>
			 <view style="margin-top:200rpx;"><u-empty text="购物车空空如也~" mode="car"></u-empty></view>
		</view>
	
		<view class="Paybtn">
			<view class="pa"><u-checkbox :checked="allchecked" :disabled="false" shape="circle" size="25" @change="selectAll"></u-checkbox></view>
			<view class="pb">全选</view>
			<view class="pc">合计：<text>￥{{total}}</text></view>
			<view class="pd" @click="JieSuan">结算{{changeStr(realBuyNum)}}</view>
		</view> <!-- Paybtn End -->
		
	</view> <!-- Contain End -->
</template>

<script setup lang='ts'>
import { ref,reactive } from 'vue'
import { onShow,onLoad } from '@dcloudio/uni-app'
import { Toast,GoUrl } from '@/utils/utils'
import { userStore } from '@/stores/userStore'
const store = userStore()

let BuyProductInfo=reactive<any>({data:null})
let allchecked=ref(false)
let ProductList=reactive<any>({data:[
	// {
	// 	"id":1,
	// 	"isOver":0,
	// 	"checked":false,
	// 	"discountPrice":120,
	// 	"picUrl":"https://i04.c.aliimg.com/img/ibank/2014/190/759/1673957091_1069217447.jpg",
	// 	"needDoctor":1,
	// 	"goodsName":"女装1",
	// 	"classifyName":"保护您的健康",
	// 	"num":1,
	// },
	// {
	// 	"id":2,
	// 	"isOver":0,
	// 	"checked":false,
	// 	"discountPrice":80,
	// 	"picUrl":"https://img1.baidu.com/it/u=2850284193,1565989185&fm=253&fmt=auto&app=138&f=JPEG?w=338&h=500",
	// 	"needDoctor":0,
	// 	"goodsName":"女装2",
	// 	"classifyName":"保护您的健康",
	// 	"num":2,
	// }
]})
let total=ref(0);
let realBuyNum=ref(0);
let Remove_del_ids=reactive<any>([])
//是否直接购买模式
let directByMode=ref(false); 
//购物车对象列表
let cartList=reactive<any>([]);
onShow(()=>{
	
			console.log("onShow 执行，是否直接购买模式",uni.getStorageSync("directByMode"))
			
			//直接购买
			if(uni.getStorageSync("directByMode")){
				addCartProductList(uni.getStorageSync("BuyProductInfo")); //转换格式
				console.log("直接购买购物车数据:",ProductList.data);
			}else{
				//购物车
				if(uni.getStorageSync("ShopCartList")){
					//转换cartList对象
					addCartProductList(uni.getStorageSync("ShopCartList"));
					/*
					cartList=uni.getStorageSync("ShopCartList");
					cartList.forEach(item=>{
						addCartProductList(item);
					});
					//*/
					uni.setStorageSync("cartProductList",ProductList.data);	
					
					//转换后，清除directByMode 和 ShopCartList
					uni.removeStorageSync("directByMode");
					uni.removeStorageSync("ShopCartList");
				}
			} 
			
			/*
			//如果非直购模式，则需转换cartList对象为BuyProductInfo对象
			if(!uni.getStorageSync("directByMode")){
				directByMode.value=uni.getStorageSync("directByMode");
				if(directByMode.value==false){
					if(uni.getStorageSync("ShopCartList")){
						//转换cartList对象
						cartList=uni.getStorageSync("ShopCartList");
						cartList.forEach(item=>{
							addCartProductList(item);
						});
						uni.setStorageSync("cartProductList",ProductList.data);	
						
						//转换后，清除directByMode 和 ShopCartList
						uni.removeStorageSync("directByMode");
						uni.removeStorageSync("ShopCartList");
					}
				}
			}
			
			//转换后读取购物车数据
			if(uni.getStorageSync("cartProductList")){
				ProductList.data=uni.getStorageSync("cartProductList")?uni.getStorageSync("cartProductList"):null;
			}else{
				if(uni.getStorageSync("BuyProductInfo")){
					BuyProductInfo.data=uni.getStorageSync("BuyProductInfo")?uni.getStorageSync("BuyProductInfo"):null;
					let index=ProductList.data.findIndex(item=>item.id===BuyProductInfo.data.id);
					if(index===-1){
						addCartProductList(BuyProductInfo.data);
					}else{
						//已存在则删除重新添加
						ProductList.data.splice(index,1);
						addCartProductList(BuyProductInfo.data);
					}
				}				
			}
			console.log("获取数据:",ProductList.data);
			//*/
			//uni.removeStorageSync("OrderNo"); //删除之前生成的订单
})
const back=()=>{
	GoUrl(store.backRouter,1);
}
const changeStr=(Num:number)=>{
	if(Num<=0) return "";
	return "("+Num+")"
}
const addCartProductList=(ProductData:any)=>{
		BuyProductInfo.data=ProductData;
		var obj:any={};
		obj.id=BuyProductInfo.data.id;
		obj.isOver=0;
		obj.checked=false;
		obj.discountPrice=BuyProductInfo.data.productdiscountprice;
		obj.picUrl=BuyProductInfo.data.productimg;
		obj.needDoctor=0;
		obj.goodsName=BuyProductInfo.data.productname;
		obj.classifyName=BuyProductInfo.data.productdesc;
		obj.num=BuyProductInfo.data.BuyNum;
		ProductList.data.push(obj);
		uni.setStorageSync("cartProductList",ProductList.data);	
}
//结算 - 购物车主要是生成订单
//1、确定购物车购买的商户后订单（调用删除订单接口删除多余)
//2、跳转到订单中心支付
const JieSuan=()=>{
	if(isComfirm_OK()===false){
		Toast("至少选择一件商品");
		return;
	}
	GoUrl("../shop_order/shop_order");			
}
//计算价格
const CountPrice=()=>{
	total.value=0;
	ProductList.data.forEach((item:any)=>{
		if(item.checked===true && item.isOver<1){
			total.value+=item.discountPrice * item.num	
		}
	})
	realBuyNum.value=GetCheckedItem();
	console.log("总价格:",total.value);			
}
//单个选中 
const ChangeItem=(index:number)=>{
	ProductList.data[index].checked=!ProductList.data[index].checked;
	if(checkAllSelect()===false){
		allchecked.value=false;
	}else{
		allchecked.value=true;
	}
	//刷新结算对象
	CountPrice();
	NoSelectProductsid();
}
//选中全部
const selectAll=()=>{
	ProductList.data.forEach((item:any,index:number)=>{
		if(allchecked.value===true){
			ProductList.data[index].checked=false;
		}else{
			ProductList.data[index].checked=true;
		}
	});
	allchecked.value=!allchecked.value;
	//刷新结算对象
	CountPrice();
}
const checkAllSelect=()=>{
	var rct=true;
	ProductList.data.forEach((item:any)=>{
		if(item.checked===false){
			rct=false;	
		}
	});	
	return rct;
}
//计算结算对象数量
const GetCheckedItem=()=>{
	let num=0;
	ProductList.data.forEach((item:any)=>{
		if(item.checked===true && item.isOver<1){
			num++;
		}
	});
	return num;
}
//确定列表至少有一件商品选中
const isComfirm_OK=()=>{
	var rct=false;
	ProductList.data.forEach((item:any)=>{
		if(item.checked===true){
			rct=true;	
		}
	});	
	return rct;	
}
//删除单个商品
const del=(index:number,id:number,name:string)=>{
	uni.showModal({
		title: '提示',
		content: "是否删除【"+name+"】该商品",
		success:(res)=>{
			if (res.confirm) {
				ProductList.data.splice(index,1);
				//刷新结算对象
				CountPrice();
				uni.setStorageSync("cartProductList",ProductList.data); //更新缓存
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
//计算没有选中的商品，移除该商品id
const NoSelectProductsid=()=>{
	Remove_del_ids=[];
	ProductList.data.forEach((item:any)=>{
		if(item.checked===false || item.isOver>=1){
			Remove_del_ids.push(item.id);
		}
	});
	console.log("要移除的购物车id:",Remove_del_ids);
}
//删除购物车
const DelCartById=(index:number)=>{
	if(Remove_del_ids[0]!=undefined){
		//移除指定元素
		ProductList.data.splice(index,1);								
	}
}
//数量增加
const boxvalChange=(index:number)=>{
   setTimeout(()=>{
	 console.log("当前对象数量:",ProductList.data[index].num);
	 CountPrice();
	 uni.setStorageSync("cartProductList",ProductList.data); //更新缓存
   },100);						
}
</script>

<style lang='scss' scoped>
	@import "shop_car.scss";
</style>